﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class MaterialWarehouseERP : BackgroundService
    {
        private readonly ILogger<MaterialWarehouseERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public MaterialWarehouseERP(ILogger<MaterialWarehouseERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时同步品号仓库信息
                //await AddMaterialWarehouse();

                await Task.Delay(24 * 60 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时同步品号仓库信息
        /// <summary>
        /// 定时同步品号仓库信息
        /// </summary>
        /// <returns></returns>
        public async Task AddMaterialWarehouse()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _wareMaterialWarehouseRep = Db.GetRepository<WareMaterialWarehouse>(services);

                var whereTime = DateTime.Now.ToString("yyyyMM");
                var whereTime1 = DateTime.Now.AddMonths(-1).ToString("yyyyMM");

                //查询近两个月的品号仓库信息
                var materialWarehouseList = await respository
                .SqlQueryAsync<MaterialWarehouseErpInput>
                (@"select MC001, --品号
	                      MC002, --仓库
	                      MC004, --安全存量
	                      MC006, --经济批量
	                      MC007  --库存数量
                   from INVMC where CREATE_DATE like '" + whereTime + "%' or CREATE_DATE like '" + whereTime1 + "%' ");

                var addMaterialWarehouseList = new List<WareMaterialWarehouse>();

                foreach (var item in materialWarehouseList)
                {
                    var isExists = await _wareMaterialWarehouseRep
                        .AnyAsync(u => u.Code.Equals(item.MC001) && u.Name.Equals(item.MC002));

                    //不存在执行新增操作
                    if (!isExists)
                    {
                        var addMaterialWarehouseModel = new WareMaterialWarehouse
                        {
                            Id = YitIdHelper.NextId(),
                            Code = item.MC001 == null ? "" : item.MC001.Trim(),
                            Name = item.MC002 == null ? "" : item.MC002.Trim(),
                            SafetyQuantity = item.MC004,
                            EconomicQuantity = item.MC006,
                            InventoryQuantity = item.MC007,
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        addMaterialWarehouseList.Add(addMaterialWarehouseModel);
                    }
                }

                // 批量新增
                await _wareMaterialWarehouseRep.InsertNowAsync(addMaterialWarehouseList);

                Console.WriteLine("定时同步品号仓库信息");
            }
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
